'use strict';
// Copyright 2014 Blueant Inc. All Rights Reserved.

/**
 * @fileoverview 士兵
 * @author sundbcn@gmail.com (sun debing)
 */

var moment = require('moment');
var _ = require('lodash');
var mongoose = require('mongoose');
var soldierItemSchema = require('./soldier/soldierItemSchema');
var soldierScheduleSchema = require('./soldier/soldierScheduleSchema');
var soldierProductItemSchema = require('./soldier/soldierProductItemSchema');
var dataApi = require('../libs/dataApi');
var soldierMgr = require('../mgr/soldierMgr');
var soldierConf = require('../config/soldierConf');
var techType = require('../consts/techType');
var sevenSoldierConf = require('../config/sevenSoldierConf.js');

///////////////////////////////////////////////////////////
/**
 * 士兵
 */
var _initSelectSoldier = function () {
    var select_soldier_list = [];
    select_soldier_list.push(2001);
    return select_soldier_list;
};

var _getSoldierId = function () {
    var task_list = [];
    dataApi.get_soldier.each(function (task_conf, task_id) {
        task_list.push(+task_id);
    });
    return task_list;
};

var soldierSchema = new mongoose.Schema({
    // 角色id
    role_id: {
        type: Number,
        required: true,
        unique: true,
        index: true
    },

    // 士兵列表
    soldier_list: [soldierItemSchema],

    // 战斗选择的兵种
    select_soldier_list: [Number],

    // 士兵战力
    soldier_power: {
        type: Number,
        default: 0
    },

    // 出战士兵战力
    select_soldier_power: {
        type: Number,
        default: 0
    },

    // 已领取活动士兵奖励列表
    receive_soldier_list: [Number],

    // 活动士兵列表
    task_list: {
        type: [Number],
        default: _getSoldierId
    },

    // // 升级排程
    // schedule_list: [soldierScheduleSchema],

    // // 生产中士兵队列
    // product_soldier_list: [soldierProductItemSchema],

    // // 已经生产完的士兵列表
    // producted_soldier_list: [soldierProductItemSchema],

    // // 生产士兵开始时间
    // start_product_time: {
    //     type: Date,
    //     default: 0
    // },

    // // 生产士兵结束时间
    // end_product_time: {
    //     type: Date,
    //     default: 0
    // },

    // // 总的生产结束时间
    // total_end_product_time: {
    //     type: Date,
    //     default: 0
    // },
});

soldierSchema.pre('save', function (next) {
    this.increment();
    if (!this.isNew && !!this.isModified()) {
        this.pushModify();
    }
    next();
});

/**
 * 记录已领取的士兵奖励id
 */
soldierSchema.methods.addReceiveRewardList = function (soldier_id) {
    var self = this;
    if (_.indexOf(self.receive_soldier_list, soldier_id) == -1) {
        self.receive_soldier_list.push(soldier_id);
        return true;
    } else {
        return false;
    }
};

soldierSchema.methods.isHaveSoldier = function (soldier_id) {
    var isVaild = false;
    _.some(this.soldier_list, function (soldier_item) {
        if (soldier_item.soldier_type == soldier_id) {
            isVaild = true;
            return true;
        }
    });
    return isVaild;
};

/**
 * 新增士兵任务刷新
 */
soldierSchema.methods.refresh = function () {
    this.refreshSoldier();
};

/**
 * 新增士兵任务刷新
 */
soldierSchema.methods.refreshSoldier = function () {
    var self = this;
    dataApi.get_soldier.each(function (task_conf, task_id) {
        if (_.indexOf(self.task_list, +task_id) == -1) {
            self.task_list.push(+task_id);
        }
    });
};

/**
 * 获取士兵星级数量
 */
soldierSchema.methods.getSoldierStarNum = function (star) {
    var total_star = 0;
    _.each(this.getSoldierList(), function (value) {
        if (value.star == star) {
            total_star++;
        }
    });
    return total_star;
};

/**
 * 获取士兵星级数量(开服七天统计使用)
 */
soldierSchema.methods.getSoldierStarNum1 = function (star) {
    var total_star = 0;
    _.each(this.getSoldierList(), function (value) {
        if (value.star >= star) {
            total_star++;
        }
    });
    return total_star;
};

/**
 * 获取士兵
 */
soldierSchema.methods.getSoldier = function (soldier_type) {
    for (var i = 0; i < this.soldier_list.length; i++) {
        var soldier = this.soldier_list[i];
        if (soldier.soldier_type == soldier_type) {
            return soldier;
        }
    }
    return null;
};

/**
 * 获取士兵列表
 */
soldierSchema.methods.getSoldierList = function () {
    return this.soldier_list;
};

/**
 * 设置选择的兵种列表
 */
soldierSchema.methods.setSelectSoldierList = function (select_list) {
    this.select_soldier_list = _.uniq(select_list);
    return true;
};

/**
 * 获取选择的兵种列表
 */
soldierSchema.methods.getSelectSoldierList = function () {
    return this.select_soldier_list;
};

/**
 * 添加一种士兵
 */
soldierSchema.methods.addSoldier = function (soldier_type, def_star) {
    // 判断该士兵类型是否存在
    if (!dataApi.soldier_type.findById(soldier_type)) {
        return false;
    }

    // 判断是否已经有该兵种
    if (!!this.getSoldier(soldier_type)) {
        return false;
    }
    var star = def_star || 1;
    var talent_type_lv_list = soldierConf.getTalentTypeLvList(soldier_type);
    for (var x = 0; x < star; x++) {
        talent_type_lv_list[x]++;
    }

    this.soldier_list.push({
        soldier_type: soldier_type,
        star: star,
        talent: talent_type_lv_list
    });
    if (this.select_soldier_list.length < 5) {
        this.select_soldier_list.push(soldier_type);
    }

    return true;
};

/**
 * 删除士兵(用于调试)
 */
soldierSchema.methods.removeSoldier = function (soldier_type) {
    var ret_code = _.remove(this.soldier_list, {
        soldier_type: soldier_type
    });
    this.markModified('soldier_list');
    return ret_code;
};

/**
 * 升级士兵
 */
soldierSchema.methods.upgradeSoldier = function (soldier_type) {
    var soldier = this.getSoldier(soldier_type);
    if (!soldier) {
        return false;
    }
    soldier.upgrade();
    return true;
};

/**
 * 获取排程列表
 * @param {[type]} soldier_type [description]
 */
soldierSchema.methods.getScheduleList = function () {
    return this.schedule_list;
};

/**
 * 获取排程
 * @param {[type]} soldier_type [description]
 */
soldierSchema.methods.getSchedule = function (soldier_type) {
    for (var i = 0; i < this.schedule_list.length; i++) {
        var schedule = this.schedule_list[i];
        if (schedule.soldier_type == soldier_type) {
            return schedule;
        }
    }
    return null;
};

/**
 * 增加一个升级排程
 * @param {[type]} soldier_type [description]
 */
soldierSchema.methods.addSchedule = function (soldier_type, need_time) {
    var soldier = this.getSoldier(soldier_type);
    if (!soldier) {
        return false;
    }
    var schedule = this.getSchedule(soldier_type);
    if (!!schedule) {
        return false;
    }
    var end_time = moment().add(need_time, 's');
    this.schedule_list.push({
        soldier_type: soldier_type,
        end_time: end_time
    });
    return true;
};

/**
 * 移除排程
 */
soldierSchema.methods.removeSchedule = function (soldier_id) {
    var schedule = this.getSchedule(soldier_id);
    if (!schedule) {
        return false;
    }
    schedule.remove();
    return true;
};

soldierSchema.methods.addAllSelectSoldierTrainExp = function () {
    var self = this;
    var add_train_exp_soldier_list = self.getSelectSoldierList();
    _.each(add_train_exp_soldier_list, function (soldier_type) {
        self.addSoldierTrainExp(soldier_type);
    });
    return add_train_exp_soldier_list;
};

/**
 * 给士兵增加精锐经验
 * @param {[type]} soldier_type [description]
 */
soldierSchema.methods.addSoldierTrainExp = function (soldier_type) {
    var soldier = this.getSoldier(soldier_type);
    if (!!soldier) {
        soldier.addTrainExp();
        return true;
    }

    return false;
};

/**
 * 获取生产中的士兵列表
 * @return {[type]} [description]
 */
soldierSchema.methods.getProductSoldierList = function () {
    return this.product_soldier_list;
};

/**
 * 获取开始生产士兵的时间
 * @return {[type]} [description]
 */
soldierSchema.methods.getBeginProductTime = function () {
    return this.start_product_time;
};

/**
 * 生产士兵
 * @param  {[type]} soldier_type [description]
 * @return {[type]}              [description]
 */
soldierSchema.methods.addProductSoldier = function (soldier_type, tech_model) {
    var product_soldier = this.getProductSoldier(soldier_type);
    if (!product_soldier) {
        this.product_soldier_list.push({
            soldier_type: soldier_type,
            num: 1
        });

        if (this.product_soldier_list.length == 1) {
            var soldier_item = this.getSoldier(soldier_type);
            var soldier_type_conf = soldierConf.getSoldierTypeConf(soldier_type);
            this.start_product_time = moment();
            var soldier_tech_sub_time = 1;
            // if (!!tech_model) {
            //     soldier_tech_sub_time = 1 - tech_model.getEffByTechType(techType.SOLDIER_TRAINING) / 100;
            // }
            this.end_product_time = moment().add(soldier_type_conf.time_cost * soldier_tech_sub_time, 's');
        }
    } else {
        product_soldier.num++;
    }

    this.calTotalProductTime();
};

/**
 * 减产士兵
 * @param  {[type]} soldier_type [description]
 * @return {[type]}              [description]
 */
soldierSchema.methods.subProductSoldier = function (soldier_type, num) {
    var product_soldier = this.getProductSoldier(soldier_type);
    if (!!product_soldier) {
        product_soldier.num -= num;
        if (product_soldier.num <= 0) {
            product_soldier.remove();
            if (this.product_soldier_list.length === 0) {
                this.start_product_time = 0;
                this.end_product_time = 0;
                this.total_end_product_time = 0;
            }
        }

        this.calTotalProductTime();
        return true;
    }
    return false;
};

/**
 * 获取生产中的士兵
 * @param  {[type]} soldier_type [description]
 * @return {[type]}              [description]
 */
soldierSchema.methods.getProductSoldier = function (soldier_type) {
    var product_soldier;
    _.some(this.product_soldier_list, function (product_soldier_item) {
        if (product_soldier_item.getSoldierType() == soldier_type) {
            product_soldier = product_soldier_item;
            return true;
        }
    });
    return product_soldier;
};

/**
 * 获取已经生产的士兵
 * @param  {[type]} soldier_type [description]
 * @return {[type]}              [description]
 */
soldierSchema.methods.getProductedSoldier = function (soldier_type) {
    var producted_soldier;
    _.some(this.producted_soldier_list, function (producted_soldier_item) {
        if (producted_soldier_item.getSoldierType() == soldier_type) {
            producted_soldier = producted_soldier_item;
            return true;
        }
    });
    return producted_soldier;
};

/**
 * 增加已经建造的士兵数量
 * @param  {[type]} soldier_type [description]
 * @return {[type]}              [description]
 */
soldierSchema.methods.getProductedSoldierNum = function (soldier_type) {
    var soldier_item = this.getProductedSoldier(soldier_type);
    if (!!soldier_item) {
        return soldier_item.num;
    }
    return 0;
};

/**
 * 添加已经生产的士兵
 * @param {[type]} soldier_type [description]
 * @param {[type]} num          [description]
 */
soldierSchema.methods.addProductedSoldierNum = function (soldier_type, num) {
    num = parseInt(num);
    var soldier_item = this.getProductedSoldier(soldier_type);
    if (!soldier_item) {
        this.producted_soldier_list.push({
            soldier_type: soldier_type,
            num: num
        });
    } else {
        soldier_item.num += num;
    }
};

soldierSchema.methods.subProductedSoldierNum = function (soldier_type, num) {
    num = parseInt(num);
    var soldier_item = this.getProductedSoldier(soldier_type);
    if (!soldier_item) {
        return false;
    }
    if (soldier_item.num < num) {
        return false;
    }
    soldier_item.num -= num;
    return true;
};

/**
 * 计算总的生产时间
 * @return {[type]} [description]
 */
soldierSchema.methods.calTotalProductTime = function () {
    var product_soldier_list = this.getProductSoldierList();
    var total_product_time = 0;
    _.each(product_soldier_list, function (product_soldier_item) {
        var soldier_type = product_soldier_item.getSoldierType();
        var num = product_soldier_item.getNum();
        total_product_time += soldierConf.getSoldierProductTime(soldier_type) * num;
    });
    this.total_end_product_time = moment(this.start_product_time).add(total_product_time, 's');
};

/**
 * 道具卡使用扣除士兵生产时间
 * @param {[type]} soldier_type [description]
 * @param {[type]} num          [description]
 */
soldierSchema.methods.subTotalEndProductTime = function (consume_value) {
    if (this.total_end_product_time > 0) {
        this.total_end_product_time -= consume_value;
        return true;
    } else {
        return false;
    }

};

/**
 * 获取修改
 * @return {[type]} [description]
 */
soldierSchema.methods.getLastChange = function () {
    var json_data = this.toJSON();
    var soldier_list = [];
    _.each(this.soldier_list, function (soldier_item) {
        if (!!soldier_item.isModified()) {
            soldier_list.push(soldier_item);
        }
    });
    json_data.soldier_list = soldier_list;
    return json_data;
};

/**
 * 推送给用户
 * @return {[type]} [description]
 */
soldierSchema.methods.push = function () {
    soldierMgr.sendSoldierChanged(
        this.role_id,
        this.toJSON(),
        function (err, fails) {
            if (err) {
                console.error('send soldier message error: %j, fail ids: %j', err, fails);
                return;
            }
        }
    );
};

soldierSchema.methods.pushModify = function () {
    soldierMgr.sendSoldierChanged(
        this.role_id,
        this.getLastChange(),
        function (err, fails) {
            if (err) {
                console.error('send soldier message error: %j, fail ids: %j', err, fails);
                return;
            }
        }
    );
};

if (!soldierSchema.options.toJSON) {
    soldierSchema.options.toJSON = {};
}
/* jshint unused:false */
soldierSchema.options.toJSON.transform = function (doc, ret) {
    delete ret.role_id;
    delete ret._id;
    delete ret.__v;
    ret.start_product_time = moment(ret.start_product_time).unix();
    ret.end_product_time = moment(ret.end_product_time).unix();
    ret.total_end_product_time = moment(ret.total_end_product_time).unix();
};

mongoose.model('Soldier', soldierSchema);
